package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dto.GoodsDTO;
import com.itheima.dto.GoodsSkuDTO;
import com.itheima.mapper.ItemSkuMapper;
import com.itheima.mapper.ItemSpuMapper;
import com.itheima.pojo.*;
import com.itheima.qo.ItemSpuQuery;
import com.itheima.qo.PageQuery;
import com.itheima.vo.PageResult;
import com.itheima.service.ItemSpuService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class ItemSpuServiceImpl implements ItemSpuService {

    private final ItemSpuMapper itemSpuMapper;
    private final ItemSkuMapper itemSkuMapper;

    @Override
    public PageResult page(PageQuery<ItemSpuQuery> pageQuery) {
        // 设置默认分页参数
        int page = (pageQuery.getPage() != null) ? pageQuery.getPage() : 1;
        int pageSize = (pageQuery.getPageSize() != null) ? pageQuery.getPageSize() : 10;

        // 设置分页插件
        PageHelper.startPage(page, pageSize);

        // 从 pageQuery 中取出查询条件对象
        ItemSpuQuery query = pageQuery.getBody();  // 可能为 null，注意判空

        // 调用 Mapper 查询
        List<ItemSpu> spuList = itemSpuMapper.listByPage(pageQuery);

        // 如果需要，可以加载 SKU 数据等
        loadSkuDataForThirdLevelCategories(spuList);

        // 构造分页结果
        Page<ItemSpu> pageInfo = (Page<ItemSpu>) spuList;
        PageResult result = new PageResult();
        result.setTotal(pageInfo.getTotal());
        result.setPages(pageInfo.getPages());
        result.setCurrentPage(page);
        result.setData(pageInfo.getResult());

        return result;
    }

    @Override
    public PageResult pageByCategory(PageQuery pageQuery, Integer categoryId1, Integer categoryId2, Integer categoryId3) {
        // 设置默认值，防止空指针异常
        int page = (pageQuery.getPage() != null) ? pageQuery.getPage() : 1;
        int pageSize = (pageQuery.getPageSize() != null) ? pageQuery.getPageSize() : 10;

        // 设置分页参数
        PageHelper.startPage(page, pageSize);

        // 查询数据
        List<ItemSpu> spuList = itemSpuMapper.listByCategoryId(categoryId1, categoryId2, categoryId3);

        // 如果是第三级分类，加载SKU信息
        if (categoryId1 != null && categoryId2 != null && categoryId3 != null) {
            loadSkuDataForThirdLevelCategories(spuList);
        }

        // 构造分页结果
        Page<ItemSpu> pageResult = (Page<ItemSpu>) spuList;
        PageResult result = new PageResult();
        result.setTotal(pageResult.getTotal());
        result.setPages(pageResult.getPages());
        result.setCurrentPage(page);
        result.setData(pageResult.getResult());

        return result;
    }

    /**
     * 为第三级分类的商品加载SKU数据
     */
    private void loadSkuDataForThirdLevelCategories(List<ItemSpu> spuList) {
        if (spuList != null && !spuList.isEmpty()) {
            for (ItemSpu spu : spuList) {
                // 查询关联的SKU信息
                List<ItemSku> skus = itemSkuMapper.listBySpuId(spu.getId());
                spu.setSkus(skus);
            }
        }
    }

    @Override
    public List<ItemSpu> listAll() {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPage(1);
        pageQuery.setPageSize(1000); // 设置一个较大的数值以获取所有数据
        return itemSpuMapper.listByPage(pageQuery);
    }

    @Override
    public GoodsDTO getById(Long id) {
        // 查询SPU信息
        ItemSpu spu = itemSpuMapper.getById(id);
        if (spu == null) {
            return null;
        }

        // 查询关联的SKU信息
        List<ItemSku> skus = itemSkuMapper.listBySpuId(id);

        // 构造GoodsDTO
        GoodsDTO goodsDTO = new GoodsDTO();
        BeanUtils.copyProperties(spu, goodsDTO);
        // 特别处理SKU列表，确保前端能正确接收
        List<GoodsSkuDTO> goodsSkus = skus.stream().map(sku -> {
            GoodsSkuDTO goodsSkuDTO = new GoodsSkuDTO();
            goodsSkuDTO.setId(sku.getId());
            goodsSkuDTO.setSkuCode(sku.getCode());
            goodsSkuDTO.setSkuName(sku.getTitle());
            goodsSkuDTO.setUnit(sku.getUnit() != null ? sku.getUnit() : ""); // 确保unit字段不为null
            goodsSkuDTO.setCode(sku.getCode());
            goodsSkuDTO.setProductWeight(sku.getProductWeight());
            goodsSkuDTO.setProductLength(sku.getProductLength());
            goodsSkuDTO.setProductWidth(sku.getProductWidth());
            goodsSkuDTO.setProductHeight(sku.getProductHeight());
            goodsSkuDTO.setProductVolume(sku.getProductVolume());
            goodsSkuDTO.setCost(sku.getRealPrice());
            goodsSkuDTO.setPrice(sku.getPrice());
            return goodsSkuDTO;
        }).collect(Collectors.toList());

        goodsDTO.setSkus(goodsSkus);
        goodsDTO.setSkuList(goodsSkus); // 同时设置skuList属性以匹配前端

        return goodsDTO;
    }

    @Override
    @Transactional
    public void save(GoodsDTO goodsDTO) {
        // 添加调试日志
        System.out.println("=== ItemSpuServiceImpl.save ===");
        System.out.println("保存商品数据: " + goodsDTO);
        if (goodsDTO != null) {
            System.out.println("商品标题: " + goodsDTO.getTitle());
        }

        // 生成SPU ID
        long spuId = System.currentTimeMillis();

        // 保存SPU信息
        ItemSpu spu = new ItemSpu();
        BeanUtils.copyProperties(goodsDTO, spu);

        // 添加额外的null检查和默认值设置
        if (spu.getTitle() == null || spu.getTitle().isEmpty()) {
            spu.setTitle("未命名商品"); // 设置默认标题
            System.out.println("标题为空，设置默认标题: 未命名商品");
        }

        spu.setId(spuId);
        spu.setCreateTime(LocalDateTime.now());
        spu.setUpdateTime(LocalDateTime.now());
        spu.setIsDel(1);
        System.out.println("即将插入的SPU数据: " + spu);
        System.out.println("SPU标题: " + spu.getTitle());
        itemSpuMapper.insert(spu);

        // 保存SKU信息
        if (!CollectionUtils.isEmpty(goodsDTO.getSkus()) || !CollectionUtils.isEmpty(goodsDTO.getSkuList())) {
            // 确定使用哪个SKU列表
            List<GoodsSkuDTO> skuList = goodsDTO.getSkus() != null ? goodsDTO.getSkus() : goodsDTO.getSkuList();

            List<ItemSku> skus = skuList.stream().map(goodsSkuDTO -> {
                ItemSku sku = new ItemSku();
                sku.setId(System.currentTimeMillis() + skuList.indexOf(goodsSkuDTO));
                sku.setSpuId(spuId);
                sku.setCode(goodsSkuDTO.getCode());
                // 确保SKU标题不为空
                String skuTitle = goodsSkuDTO.getSkuName() != null ? goodsSkuDTO.getSkuName() :
                        (goodsSkuDTO.getTitle() != null ? goodsSkuDTO.getTitle() : goodsSkuDTO.getCode());
                sku.setTitle(skuTitle);
                sku.setUnit(goodsSkuDTO.getUnit());
                sku.setProductWeight(goodsSkuDTO.getProductWeight());
                sku.setProductLength(goodsSkuDTO.getProductLength());
                sku.setProductWidth(goodsSkuDTO.getProductWidth());
                sku.setProductHeight(goodsSkuDTO.getProductHeight());
                sku.setProductVolume(goodsSkuDTO.getProductVolume());
                sku.setPrice(goodsSkuDTO.getPrice());
                sku.setRealPrice(goodsSkuDTO.getCost() != null ? goodsSkuDTO.getCost() : goodsSkuDTO.getRealPrice());
                sku.setCreateTime(LocalDateTime.now());
                sku.setUpdateTime(LocalDateTime.now());
                sku.setIsDel(1);
                sku.setSaasId(spu.getSaasId());
                sku.setCreateBy(spu.getCreateBy());
                sku.setUpdateBy(spu.getUpdateBy());
                System.out.println("即将插入的SKU数据: " + sku);
                return sku;
            }).collect(Collectors.toList());

            itemSkuMapper.batchInsert(skus);
        }
    }

    @Override
    @Transactional
    public void update(GoodsDTO goodsDTO) {
        // 更新SPU信息
        ItemSpu spu = new ItemSpu();
        BeanUtils.copyProperties(goodsDTO, spu);
        spu.setUpdateTime(LocalDateTime.now());
        itemSpuMapper.update(spu);

        // 删除原有的SKU信息
        itemSkuMapper.deleteBySpuId(goodsDTO.getId());

        // 重新保存SKU信息
        if (!CollectionUtils.isEmpty(goodsDTO.getSkus()) || !CollectionUtils.isEmpty(goodsDTO.getSkuList())) {
            // 确定使用哪个SKU列表
            List<GoodsSkuDTO> skuList = goodsDTO.getSkus() != null ? goodsDTO.getSkus() : goodsDTO.getSkuList();

            List<ItemSku> skus = skuList.stream().map(goodsSkuDTO -> {
                ItemSku sku = new ItemSku();
                sku.setId(System.currentTimeMillis() + skuList.indexOf(goodsSkuDTO));
                sku.setSpuId(goodsDTO.getId());
                sku.setCode(goodsSkuDTO.getCode());
                // 确保SKU标题不为空
                String skuTitle = goodsSkuDTO.getSkuName() != null ? goodsSkuDTO.getSkuName() :
                        (goodsSkuDTO.getTitle() != null ? goodsSkuDTO.getTitle() : goodsSkuDTO.getCode());
                sku.setTitle(skuTitle);
                sku.setUnit(goodsSkuDTO.getUnit());
                sku.setProductWeight(goodsSkuDTO.getProductWeight());
                sku.setProductLength(goodsSkuDTO.getProductLength());
                sku.setProductWidth(goodsSkuDTO.getProductWidth());
                sku.setProductHeight(goodsSkuDTO.getProductHeight());
                sku.setProductVolume(goodsSkuDTO.getProductVolume());
                sku.setPrice(goodsSkuDTO.getPrice());
                sku.setRealPrice(goodsSkuDTO.getCost() != null ? goodsSkuDTO.getCost() : goodsSkuDTO.getRealPrice());
                sku.setCreateTime(LocalDateTime.now());
                sku.setUpdateTime(LocalDateTime.now());
                sku.setIsDel(1);
                return sku;
            }).collect(Collectors.toList());

            itemSkuMapper.batchInsert(skus);
        }
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        // 删除SPU信息（逻辑删除）
        ItemSpu spu = new ItemSpu();
        spu.setId(id);
        spu.setIsDel(2); // 设置为已删除状态
        spu.setUpdateTime(LocalDateTime.now());
        itemSpuMapper.update(spu); // 修复变量名错误

        // 删除关联的SKU信息（逻辑删除）
        itemSkuMapper.deleteBySpuId(id);
    }
}